import Vue from 'vue'

function Store(options = {}) {
  const { state = {}, mutations = {},getters={} } = options

  this._vm = new Vue({
    data: {
      // 把外面传递的state保存起来，变成响应式数据
      $$state: state
    }
  })

  // 把外面传递进来的mutations保存起来
  this._mutations = mutations

  // 把外面传递进来的getters保存起来
  this._getters = getters
}

// 自定义commit函数
Store.prototype.commit = function(type, payload) {
  if (this._mutations[type]) {
    this._mutations[type](this.state, payload)
  }
}

// 监听state的获取
// Object.defineProperty(Store.prototype, 'state', {
//   get() {
//     return this._vm._data.$$state
//   }
// })
Object.defineProperties(Store.prototype, {
  state: {
    get() {
      return this._vm._data.$$state
    }
  }
})

export default {
  Store
}
